package kpi.java_training.domain.teaching;

import kpi.java_training.domain.questions.QuestionData;

/**
 * Created by Alex Kebkalo on 12.11.13.
 * class implements list of questions with methods to perform teaching
 */
public class Teacher {
    private final int CORRECT_ANSWERS_THRESHHOLD = 3;
    private TeachingQuestionList questions;
    private int correctAnswers;
    private int nextQuestion;
    private boolean done;
    private String topic;

    public Teacher(TeachingQuestionList questions, String topic) {
        this.questions = questions;
        this.topic = topic;
        questions.sortByComplexity();
        done = false;
        setStartQuestion();
    }

    private void setStartQuestion() {
        int currentComplexity = 0;
        int questionsNumber = 0;

        if (questions.size() == 0) {
            return;
        }
        for (int i = 0; i < questions.size(); i++) {
            currentComplexity += questions.getComplexity(i)*questions.getBucketSize(i);
            questionsNumber += questions.getBucketSize(i);
        }
        currentComplexity /= questionsNumber;
        int i = questions.size()-1;
        while (questions.getComplexity(i) > currentComplexity) {
            i--;
        }
        nextQuestion = i;
        correctAnswers = 0;
    }

    public boolean parseUserAnswer(String userAnswer) {
        boolean isCorrect = questions.parseUserAnswer(nextQuestion, userAnswer);
        if (questions.getBucketSize(nextQuestion) == 0) {
            questions.remove(nextQuestion);
            checkIfDone();
            correctAnswers = 0;
        }
        if (isCorrect) {
            raiseComplexity();
        } else {
            lowerComplexity();
        }
        return isCorrect;
    }

    public String getDoneMessage() {
        return String.format("Learning %s complete!\n", topic);
    }

    public QuestionData getQuestionData() {
        return questions.getQuestionData(nextQuestion);
    }

    private void raiseComplexity() {
        correctAnswers++;
        if (correctAnswers >= CORRECT_ANSWERS_THRESHHOLD) {
            nextQuestion++;
            checkIfDone();
            correctAnswers = 0;
        }
    }

    private void checkIfDone() {
        if (nextQuestion >= questions.size()) {
            done = true;
        }
    }

    private void lowerComplexity() {
        correctAnswers = 0;
        if (nextQuestion > 0) {
            nextQuestion--;
        }
    }

    public boolean teachingDone() {
        return done;
    }
}
